import { Component, OnInit } from '@angular/core';
import { SelfCheckListService } from '../../../../services/project/self-check/self-check-list.service';
import { searchModel } from './self-check-list.model';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment-timezone';

export interface Data {
  id: number;
  name: string;
  age: number;
  address: string;
  disabled: boolean;
}
@Component({
  selector: 'app-self-check-list',
  templateUrl: './self-check-list.component.html',
  styleUrls: ['./self-check-list.component.scss']
})
export class SelfCheckListComponent implements OnInit {

  constructor(
    private router: Router,
    private selfCheckListService: SelfCheckListService,
    private routerInfo: ActivatedRoute
  ) { }

  public searchModel = new searchModel();
  public nzTotal = 0;
  public recordList: Array<object> = [];
  public isModalVisible = false;
  public detailInfo: any = {};
  public nzPageIndex = 1;
  public allChecked = false; // 全选状态
  public indeterminate = false; // 半选状态
  public checkedDatas: any = []; // 当前选中的数据集合
  public annex: any = [];  // 附件地址集合
  public annexForVideo = [];
  public annexForImg = [];
  public isviewImg;
  public curl; // 当前点击的图片地址
  public formInfo: any = {
    selectedType: '0',
    selectedStauts: '0',
    startValue: null,
    endValue: null
  };

  routeToSurvey() {
    const projectId = JSON.parse(window.localStorage.getItem('project')).id;
    this.router.navigate([`/inner/project/${projectId}/survey`], {queryParams: { info: 'project' }});
  }
  public name: string = JSON.parse(window.localStorage.getItem('project')).name;

  public async getPageInfo() {
    // const projectId = this.routerInfo.snapshot.params['projectId'];
    this.searchModel.projectId = JSON.parse(window.localStorage.getItem('project')).id;
    // this.searchModel.projectId = 'fd61f583-1d6d-4db5-bbe6-94ef24a6cf31'
    const result = await this.selfCheckListService.QuerySelfChecksPagedList(this.searchModel);
    this.nzTotal = result.result.totalCount;
    this.recordList = result.result.items;
  }

  public async getDetail(id) {
    const result = await this.selfCheckListService.QuerySelfCheckDetailById({ input: id });
    this.detailInfo = result.result;
    this.annex = result.result.attachments;
    // console.log( this.annex.splice(-3, 3));
    this.annex.forEach(element => {
      //  console.log(element.split('.')[element.split('.').length - 1]);
      if (element.split('.')[element.split('.').length - 1] == 'mp4') {
        this.annexForVideo.push(element)
      } else {
        this.annexForImg.push(element)
      }
    });

    this.isModalVisible = true;
  }

  // 预览文件
  viewImg(url) {
    this.curl = url;
    this.isviewImg = true;
  }
  // 关闭预览
  handleCancel() {
    this.isviewImg = false;
  }
  closemodal() {
    this.isModalVisible = false;
    this.annexForVideo = [];
    this.annexForImg = []
  }
  // public async deleteLot() {
  //   let checkArray = []
  //   this.checkedDatas.forEach(element => {
  //     if (element.checked) {
  //       checkArray.push(element.id)
  //     }
  //   });
  //   const result = await this.InspectionRecordsService.BatchRemoveChecks({input: checkArray})
  //   console.log(result)
  // }

  public async pageChange(index) {
    this.searchModel.skipCount = index - 1;
    await this.getPageInfo();
  }

  /**
 * 表格操作相关
 */
  private refreshCheckboxStatus() {
    const dataList = this.recordList;
    const allChecked = dataList.filter((value: any) => !value['disabled']).every((value: any) => value['checked'] === true);
    const allUnChecked = dataList.filter((value: any) => !value['disabled']).every((value: any) => !value['checked']);

    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);

    // 获取当前选中的数据
    const checkedDatas = [];
    dataList.forEach((data) => {
      if (data['checked']) {
        checkedDatas.push(data);
      }
    });
    this.checkedDatas = checkedDatas;
    console.log(this.checkedDatas);
    // 改变批量操作按钮状态
    // this.delBtnStatus = !dataList.some((value: any) => value['checked']);
  }

  checkAll(status: any, callBack?: Function): void {
    this.recordList.forEach((data: any) => {
      let eachStatus;
      if (callBack) {
        eachStatus = callBack(data);
      }
      if (eachStatus !== false) {
        data['checked'] = status;
      }
    });
    this.refreshCheckboxStatus();
  }

  /**
   * 搜索条件
   * @param date
   */
  onStartChange(date: Date): void {
    if (date) {
      this.formInfo.startValue = moment.tz(date, 'Asia/Chongqing').local().format('YYYY-MM-DD');
      this.searchModel.checkDateRange[0] = this.formInfo.startValue;
    } else {
      this.searchModel.checkDateRange.splice(0, 1)
    }
  }

  onEndChange(date: Date): void {
    if (date) {
      this.formInfo.endValue = moment.tz(date, 'Asia/Chongqing').local().format('YYYY-MM-DD');
      this.searchModel.checkDateRange[1] = this.formInfo.endValue;
    } else {
      this.searchModel.checkDateRange.splice(1, 1)
    }
  }
  ngOnInit() {
    this.getPageInfo();
  }

}
